package top.xunfong.util;

import top.xunfong.domain.ColumnInfo;
import top.xunfong.domain.TableInfo;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: xunfong
 * @date: 2025/10/17 7:58
 */
public class GenerationUtil {
    public static List<TableInfo> getTables(String url, String username, String password, String tableName) throws SQLException {
        List<TableInfo> tables = new ArrayList<>();

        try (Connection conn = DriverManager.getConnection(url, username, password)) {
            DatabaseMetaData metaData = conn.getMetaData();
            ResultSet tableResult = metaData.getTables(null, null, tableName, new String[]{"TABLE"});

            while (tableResult.next()) {
                String tableName1 = tableResult.getString("TABLE_NAME");
                String remarks = tableResult.getString("REMARKS");
                TableInfo tableInfo = TableInfo.builder()
                        .tableName(tableName)
                        .columns(getColumns(metaData, tableName))
                        .remarks(remarks).build();
                tables.add(tableInfo);
            }
        }
        return tables;
    }

    /**
     * 获取行信息
     *
     * @param metaData
     * @param tableName
     * @return
     * @throws SQLException
     */

    private static List<ColumnInfo> getColumns(DatabaseMetaData metaData, String tableName) throws SQLException {
        List<ColumnInfo> columns = new ArrayList<>();

        ResultSet columnResult = metaData.getColumns(null, null, tableName, null);
        while (columnResult.next()) {
            ColumnInfo column = ColumnInfo.builder()
                    .columnName(columnResult.getString("COLUMN_NAME"))
                    .dataType(columnResult.getString("TYPE_NAME"))
                    .remarks(columnResult.getString("REMARKS"))
                    .isNullable(columnResult.getString("IS_NULLABLE"))
                    .build();
            columns.add(column);
        }
        return columns;
    }
}
